package com.copractice.beans.common;

import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

/**
 * Contains methods for working with messages for presentation layer.
 *
 * @author Dmitry Churbanov (dmitry.churbanov@gmail.com)
 * @version 1.0 03/17/2009
 */
public class MessagesUtil {
    
    private MessagesUtil(){}

    /**
     * Adds message to the current instance of <code>FacesContext</code>.
     * 
     * @param component component for which message is
     * @param messageBundleName name of a bundle where message should be found
     * @param messageBundleText name of a message to show
     */
    public static void addMessage(UIComponent component, String messageBundleName, String messageBundleText) {
        final FacesContext context = FacesContext.getCurrentInstance();
        if (component != null) {
            context.addMessage(component.getClientId(context), getFacesMessage(messageBundleName, messageBundleText));
        } else {
            context.addMessage(null, getFacesMessage(messageBundleName, messageBundleText));
        }
    }

    public static FacesMessage getFacesMessage(String messageBundleName, String messageBundleText) {
        return new FacesMessage(getBundleMessage(messageBundleName, messageBundleText));
    }

    public static String getBundleMessage(String messageBundleName, String messageBundleText) {
        if (messageBundleName == null) {
            messageBundleName = Constants.MESSAGE_BUNDLE;
        }
        return ResourceBundle.getBundle(messageBundleName).getString(messageBundleText);
    }

}
